<script setup lang="ts">
import { reactive ,ref} from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
// Register.vue <script setup>
import { useUserStore } from '@/stores/user'   // 路径按实际来
const userStore = useUserStore()
// const router = useRouter()  // 创建 router 实例


import request from '@/utils/request.ts'
import {ElMessage} from "element-plus";

// import { useUserStore } from '@/store/user.ts'
// 表单响应式数据定义
let registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phonenumber: ''
})

let registerRef = ref()

// 验证密码⼀致性
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
 if (value === '') {
 callback(new Error('请再次输⼊密码'))
 } else if (value !== registerForm.password) {
 callback(new Error('两次输⼊密码不⼀致!'))
 } else {
 callback()
 }
}

let registerRules = {
  username: [
    { required: true, message: '请输⼊⽤户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输⼊密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur'
    }
  ],
  email: [
    { type: 'email', trigger: 'blur', message: '请输⼊正确的邮箱地址' }
  ],
  // phonenumber: [
  //     { pattern: /^1[3-9]\d{9}$/, trigger: 'blur', message: '请输⼊正确的⼿机号' }
  // ]
}


// let handleRegister = () =>{
//   registerRef.value.validate(()=>{
//     console.log('提交表单')
//     console.log(registerForm)
    // userStore.register{
    //   {
    //     username: registerForm.username,
    //     password: registerForm.password,
    //     email: registerForm.email,
    //     phonenumber: registerForm.phonenumber
    //   }
    // }
//   })
// }

let loading = ref(false) // 注册按钮加载状态

let handleRegister = async () => {
  /**
   * 表单验证函数
   * 该函数用于触发表单验证，并在验证完成后执行回调函数
   * @param {Function} callback - 验证完成后的回调函数
   * @returns {void}
   */
  if (!registerRef.value) return  // 验证表单
  await registerRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    registerRef.value.validate(async () => {
      // 验证完成后输出表单数据
      console.log(registerForm)
      // 发送注册表单信息
      try {
        loading.value = true
        const result = await userStore.register(
          {
            username: registerForm.username, // 用户名
            password: registerForm.password, // 密码
            email: registerForm.email, // 邮箱
            phonenumber: registerForm.phonenumber // 手机号
          }
        )
        if (result.success){
          ElMessage.success('注册成功')
          router.push('/login')
        }else {
          ElMessage.error(result.message)
        }
      }
      catch (error : any) {
        ElMessage.error(error.response.data.message)
        console.log(error)
      }
      finally {
        loading.value = false
      }
    })

  })
}

let handleLogin = () => {
  router.push('/login')
}
</script>

<template>
<div class="register">
  <el-form
    ref="registerRef"
    class="register-form"
    :model="registerForm"
    :rules="registerRules"
  >
    <h3 class="title">⽤户注册</h3>
    <el-form-item prop="username">
      <el-input
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输⼊⽤户名"
          prefix-icon="User"
          v-model="registerForm.username"
      >
      </el-input>
    </el-form-item>

    <el-form-item prop="password">
      <el-input
          type="password"
          size="large"
          auto-complete="off"
          placeholder="请输⼊密码"
          prefix-icon="Lock"
          show-password
          style="margin-top: 20px"
          v-model="registerForm.password"
      >
      </el-input>
    </el-form-item>

    <el-form-item prop="confirmPassword">
      <el-input
          type="password"
          size="large"
          auto-complete="off"
          placeholder="请确认密码"
          prefix-icon="Lock"
          show-password
          style="margin-top: 20px"
          v-model="registerForm.confirmPassword"
      >
    </el-input>
    </el-form-item>

    <el-form-item prop="email">
      <el-input
          type="email"
          size="large"
          auto-complete="off"
          placeholder="请输⼊邮箱（可选）"
          prefix-icon="Message"
          style="margin-top: 20px"
          v-model="registerForm.email"
      >
      </el-input>
    </el-form-item>

    <el-form-item prop="phonenumber">
      <el-input
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输⼊⼿机号（可选）"
          prefix-icon="Phone"
          style="margin-top: 20px"
          v-model="registerForm.phonenumber"
      >
      </el-input>
    </el-form-item>

    <el-form-item style="width:100%;">
      <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width:100%; margin-top: 20px"

          @click="handleRegister"
      >
      <span>{{loading ? '注 册中' : '注 册'}}</span>
      </el-button>
    </el-form-item>

    <div class="login-link">
      <span>已有账号？</span>

      <el-link type="primary" @click="handleLogin" >
      ⽴即登录
      </el-link>
<!--      <el-link type="primary" @click="router.push('/login')">-->
<!--      ⽴即登录-->
<!--      </el-link>-->
    </div>
  </el-form>
</div>

</template>

<style scoped lang="scss">
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("@/assets/images/bg.png");
  background-size: cover;

  .register-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 25px 25px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .title {
      margin: 0px auto 30px auto;
      text-align: center;
      color: #707070;
      font-size: 20px;
      font-weight: bold;
    }

    .el-input {
      height: 40px;

      :deep(.el-input__wrapper) {
        padding: 0 15px;
      }
    }

    .login-link {
      text-align: center;
      margin-top: 20px;
      font-size: 14px;
      color: #606266;
    }
  }
}


</style>